package com.lubase.metadata.tabletrigger;

import com.lubase.model.DbEntity;
import com.lubase.model.DbTable;
import com.lubase.orm.QueryOption;
import com.lubase.orm.TableFilter;
import com.lubase.orm.extend.ITableTrigger;
import com.lubase.model.DbCollection;
import com.lubase.orm.service.DataAccess;
import com.lubase.orm.util.TypeConverterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MtConstraintTrigger implements ITableTrigger {
    @Autowired
    DataAccess dataAccess;

    @Override
    public String getTriggerTableCode() {
        return "mt_constraint";
    }

    @Override
    public String getTriggerName() {
        return "mt_constraint";
    }

    @Override
    public Boolean isDelete() {
        return true;
    }

    @Override
    public Boolean beforeValidate(DbTable tableInfo, DbEntity entity, Boolean isServer) throws Exception {
        QueryOption queryOption = new QueryOption("mt_constraint");
        queryOption.setTableFilter(new TableFilter("id", entity.getId().toString()));
        queryOption.setFixField("from_database");
        DbCollection collConstraint = dataAccess.queryAllData(queryOption);
        if (collConstraint != null && collConstraint.getData() != null && !collConstraint.getData().isEmpty()) {
            DbEntity constraintEntity = collConstraint.getData().get(0);
            String fromDatabase = TypeConverterUtils.object2String(constraintEntity.get("from_database"), "");
            return !fromDatabase.equals("1");
        }
        return true;
    }
}
